<template>
  <div class="content">
    <div class="pageSearchView">
      <el-form :inline="true" :model="searchParam" class="demo-form-inline">
        <el-form-item label="计划名称">
          <el-input v-model="searchParam.name" placeholder="请输入计划名称" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="设备编码">
          <el-input v-model="searchParam.equipmentCode" placeholder="请输入设备编码" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="所属部门">
          <el-tree-select v-model="searchParam.organizationId" :data="workRoomList" check-strictly
                          :props="{ children: 'sonList', label: 'orgName', value: 'id' }" style="width: 200px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleSearch">查询</el-button>
          <el-button icon="Refresh" @click="resetSearch()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="pageTableView">
      <el-tabs v-model="activeName" type="card" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane label="未完成" name="CREATED">
          <div class="pageTableMenuView">
            <div class="pageTableTitle">
              保养列表信息
              <el-icon>
                <house-icon/>
              </el-icon>
            </div>
          </div>
          <Unfinished :paginationParams="paginationParams" :pageTotal="pageTotal" :taskNoPage="taskNoPage"
                      :onSubmit="onSubmit" :fetchPage="fetchPage" :equipmentData="equipmentData"
                      :handleSizeChange="handleSizeChange" :handleCurrentChange="handleCurrentChange"/>
        </el-tab-pane>
        <el-tab-pane label="已完成" name="FINISHED">
          <div class="pageTableMenuView">
            <div class="pageTableTitle">
              列表信息
              <el-icon>
                <house-icon/>
              </el-icon>
            </div>
          </div>
          <Finish :paginationParams="paginationParams" :pageTotal="pageTotal" :taskNoPage="taskNoPage"
                  :onSubmit="onSubmit" :fetchPage="fetchPage" :equipmentData="equipmentData"
                  :handleSizeChange="handleSizeChange" :handleCurrentChange="handleCurrentChange"/>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup>
import SearchForm from '@/components/SearchForm.vue';
import {useToolData} from '@/hooks/baseData/tooling';
import axiosInstance from "@/utils/http/api";
import {Delete, Edit, Plus} from '@element-plus/icons-vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import {computed, onMounted, ref, onBeforeUnmount} from 'vue';
import Unfinished from './unfinished.vue'
import Finish from './finish.vue'
import {equipmentAll, equipmentInspectionTaskPage, equipmentInspectionTaskUpdate} from '@/api/device/pointInspection'

const activeName = ref('CREATED')
const searchParam = ref({})
const searchFields = ref([
  {
    name: "name",
    label: "计划名称",
    component: "input",
    placeholder: "",
    class: "!w-[350px]",
  },
  {
    name: "equipmentCode",
    label: "设备编码",
    component: "input",
    placeholder: "",
    class: "!w-[350px]",
  },
])

// 缓存键名
const CACHE_KEY = 'equipment_inspection_search_cache';

// 加载缓存的搜索条件
const loadSearchCache = () => {
  const cache = sessionStorage.getItem(CACHE_KEY);
  if (cache) {
    try {
      const parsed = JSON.parse(cache);
      if (parsed.searchParam) searchParam.value = parsed.searchParam;
      if (parsed.activeName) activeName.value = parsed.activeName;
      if (parsed.paginationParams) paginationParams.value = parsed.paginationParams;
    } catch (e) {
      console.error('解析搜索缓存失败', e);
    }
  }
};

// 保存搜索条件到缓存
const saveSearchCache = () => {
  const cacheData = {
    searchParam: {...searchParam.value},
    activeName: activeName.value,
    paginationParams: {...paginationParams.value}
  };
  sessionStorage.setItem(CACHE_KEY, JSON.stringify(cacheData));
};

// 清除搜索缓存
const clearSearchCache = () => {
  sessionStorage.removeItem(CACHE_KEY);
};

const resetSearch = () => {
  searchParam.value = {};
  paginationParams.value = {pageSize: 10, current: 1};
  saveSearchCache(); // 保存重置后的状态
  fetchPage();
};

const pageTotal = ref(0);
const taskNoPage = ref([]);
const equipmentData = ref([]);
const paginationParams = ref({pageSize: 10, current: 1});

onMounted(() => {
  loadSearchCache(); // 加载缓存
  fetchPage();
  fetchAll();
});

// 组件卸载前保存当前状态
onBeforeUnmount(() => {
  saveSearchCache();
});

const fetchAll = () => {
  equipmentAll({}).then(res => {
    equipmentData.value = res.data;
  });

  axiosInstance.post('/api/basedataOrganization/getAll', {})
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        workRoomList.value = res.data;
      });
};

const workRoomList = ref([]);//车间

const fetchPage = () => {
  saveSearchCache(); // 每次查询前保存当前状态

  let statusList = ['EXECUTING', 'CREATED'];
  if (activeName.value === 'FINISHED') {
    statusList = ['FINISHED'];
  }

  equipmentInspectionTaskPage({
    ...paginationParams.value,
    ...searchParam.value,
    statusList,
    equipmentInspectionType: 1,
    type: 1,
  }).then(res => {
    taskNoPage.value = res.data.records;
    pageTotal.value = res.data.total;
  });
};

const handleSearch = () => {
  paginationParams.value.current = 1; // 搜索时重置到第一页
  fetchPage();
};

const handleClick = (tab, event) => {
  activeName.value = tab.props.name;
  paginationParams.value.current = 1; // 切换标签时重置到第一页
  fetchPage();
};

const onSubmit = (params, callback) => {
  equipmentInspectionTaskUpdate(params).then(res => {
    if (res.code === 200) {
      ElMessage.success('操作成功');
      fetchPage();
      callback();
    } else {
      ElMessage.error(res.message);
    }
  });
};

const handleSizeChange = (val) => {
  paginationParams.value.pageSize = val;
  fetchPage();
};

const handleCurrentChange = (val) => {
  paginationParams.value.current = val;
  fetchPage();
};
</script>

<style scoped></style>